package com.ytzl.itrip.service.userinfo.impl;

import com.alibaba.fastjson.JSON;
import com.ytzl.itrip.pojo.po.userinfo.ItripUser;
import com.ytzl.itrip.service.userinfo.TokenService;
import com.ytzl.itrip.util.MD5;
import com.ytzl.itrip.util.RedisAPI;
import com.ytzl.itrip.util.UserAgentUtil;
import cz.mallat.uasparser.UserAgentInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;


import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Description: 本类用于
 * Created by gengshu on 2019/12/26 9:38
 */
@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private RedisAPI redisAPI;
    /**
     *  客户端信息+ 邮箱的md5（32位）+ 用户id + 当前时间年月日时分秒 + agent的6位码
     * @param agent
     * @param user
     * @return
     */
    @Override
    public String generatorToken(String agent, ItripUser user) {

        try {
            UserAgentInfo userAgentInfo = UserAgentUtil.getUasParser().parse(agent);
            String userAgentInfoDeviceType = userAgentInfo.getDeviceType();
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("token: ");
            if (UserAgentInfo.UNKNOWN.equals(userAgentInfoDeviceType)){
                if (UserAgentUtil.CheckAgent(agent)){
                    stringBuffer.append("MOBILE- ");
                }else{
                    stringBuffer.append("PC- ");
                }
            }
            stringBuffer.append(MD5.getMd5(user.getUserCode(),32)+"-");
            stringBuffer.append(user.getId()+"-");
            stringBuffer.append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
            stringBuffer.append(MD5.getMd5(agent,6));
            RedisAPI redisAPI = new RedisAPI();
            JedisPool jedisPool = redisAPI.createJedisPool();
            Jedis jedis = jedisPool.getResource();
            jedis.set("Token",stringBuffer.toString());
            return stringBuffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void saveToken(String key,ItripUser itripUser){
        redisAPI.set(key, JSON.toJSONString(itripUser));
    }

}
